from datetime import datetime
from rest_framework.views import APIView
from utils.response import ApiResponse
import os,uuid
from django.conf import settings


class UploaderView(APIView):
  def post(self, request):
        
        if 'file' not in request.FILES:
            return ApiResponse.error(message='没有上传任何文件')
        
        uploaded_file = request.FILES['file']
        
        # 处理文件名
        original_name = uploaded_file.name
        ext = os.path.splitext(original_name)[1]

        new_filename = f"{uuid.uuid4().hex}{ext}"
        today = datetime.now().strftime('%Y-%m-%d')
        upload_dir = os.path.join(settings.MEDIA_ROOT, 'uploads',today)
        save_path = os.path.join(upload_dir, new_filename)
        
        # 确保目录存在
        os.makedirs(upload_dir, exist_ok=True)
        
        try:
            # 保存文件
            with open(save_path, 'wb+') as destination:
                for chunk in uploaded_file.chunks():
                    destination.write(chunk)
            
            # 验证文件是否保存成功
            if not os.path.exists(save_path):
                return ApiResponse.error(message='文件保存失败')
            
            file_size = os.path.getsize(save_path)
            
            # 构建访问 URL
            file_url = os.path.join(settings.MEDIA_ROOT,'uploads/',today,new_filename)
            #file_url = file_url.replace('\\', '/')
            file_url = os.path.normpath(file_url).replace('\\', '/')
            return ApiResponse(data={
                'status': 'success',
                'original_name': original_name,
                'saved_name': new_filename,
                'file_url': file_url,
                'size': file_size
            })
            
        except Exception as e:
            return ApiResponse(code=500, message=str(e))
    